import emitter from '../emitter'
import NoMore from '../components/NoMore.vue'

const LOAD_LIMIT = 12 // 分页数量
export default {
  data() {
    return {
      items: [],
      hasMore: true,
      showMoreLoading: false,
      page: 1,
      loadDone: false,
      loading: false
    }
  },

  components: { NoMore },

  mounted() {
    emitter.on('scroll-to-bottom', this.fetch.bind(this, false))
  },

  methods: {
    fetch(fresh = true) {
      if (!this.paging) {
        return
      }

      if (fresh) {
        this.hasMore = true
        this.page = 1
      }

      if (!this.hasMore || this.showMoreLoading || this.loading) {
        return Promise.resolve()
      }

      this.loadDone = false
      this.loading = true
      if (this.page === 1) {
        this.showLoading()
      } else {
        this.showMoreLoading = true
      }

      return this.$post(this.paging.path, {
        ...this.paging.params,
        limit: LOAD_LIMIT,
        page: this.page
      }).then(items => {
        if (items.length && this.config.env.isApp && this.$route.name !== 'history-list') {
          this.action('getKeywordAdv', this.paging.params.keyword).then(res => {
            if (res) {
              items.splice(1, 0, res)
            }
          })
        }
        if (this.page === 1) {
          this.items = items
        } else {
          this.items.push(...items)
        }
        this.page = this.page + 1
        this.hasMore = fresh ? items.length === LOAD_LIMIT : items.length > 0
        this.loadCallback()
      }).catch(this.loadCallback.bind(this))
    },

    loadCallback() {
      this.hideLoading()
      this.showMoreLoading = false
      this.loadDone = true
      this.loading = false
    }
  }
}
